<template>
  <ie-page>

    <template #extra>
      <n-space>
        <n-upload
          action="/api/upload"
          @finish="onUploadFinish"
          accept=".pdf,.jpg,.jpeg,.png"
          :headers="getHeaders"
          :show-file-list="false"
        >
          <n-button type="primary">上传文件</n-button>
        </n-upload>
      </n-space>
    </template>

    <ie-table-query :model="AttachmentModel" />

    <ie-table
      :model="AttachmentModel"
      :actions="['delete']"
      @delete:row="handleDelete"
      ref="tableRef"
    />

  </ie-page>
</template>

<script setup>
import { ref } from 'vue'

import AttachmentModel from '/@/model/attachment'
import { useApi, getHeaders } from '/@/api'

const tableRef = ref()

function onUploadFinish() {
  tableRef.value?.refresh()
}

function downloadRow(row) {
  const { id, filename } = row

  if (id) {
    const a = document.createElement('a')

    a.href = filename
    a.download = filename
    document.body.appendChild(a)
    a.click()
    a.remove()
  }
}

function handleDelete(row, refresh) {
  useApi()
    .post('upload/' + row.id + '/delete', null, {
      authorize: true,
      prefixUrl: '/api'
    })
    .then(refresh)
}
</script>